<template>
  <div class="news-detail-selector">
    <el-row style="margin: 10px 0 0" :gutter="10">
      <el-col :span="6">
        <el-input v-model="title" placeholder="请输入名称" @change="reload" clearable />
      </el-col>
      <el-col :span="4">
        <el-button type="small"  @click="reload" clearable>查询</el-button>
      </el-col>
      <el-col :span="10">
        <el-radio-group v-model="type" @change="reload">
          <el-radio-button label>全部</el-radio-button>
          <el-radio-button :label="1">普通新闻</el-radio-button>
          <el-radio-button :label="2">党建新闻</el-radio-button>
        </el-radio-group>
      </el-col>
    </el-row>

    <el-table
      :data="newsList"
      ref="tab"
      border
      height="250"
      @current-change="onSelectRow"
      highlight-current-row
    >
      <el-table-column prop="title" label="新闻标题" />
      <el-table-column label="新闻类型">
        <template slot-scope="scope">
          <el-tag v-if="parseInt(scope.row.type) === 1">普通新闻</el-tag>
          <el-tag type="danger" v-else>党建新闻</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="pageSizeChange"
      @current-change="pageIndexChange"
      :current-page.sync="pageIndex"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newsList: [],
      type: null,
      title: '',
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0
    }
  },
  props: {
    selectedId: {
      type: String,
      required: false,
      default: ''
    }
  },
  methods: {
    pageIndexChange(val) {
      this.pageIndex = val
      this.loadMore()
    },
    pageSizeChange(val) {
      this.pageSize = val
      this.loadMore()
    },
    async reload() {
      await this.loadMore(1)
    },
    async loadMore(pageIndex) {
      if (pageIndex) this.pageIndex = pageIndex
      var res = await this.$http.post('/news-admin/news/list', {
        title: this.title,
        type: this.type,
        page: this.pageIndex,
        limit: this.pageSize
      })
      this.totalCount = res.data.totalCount
      this.newsList = res.data.list
      // this.pageIndex++
    },
    onSelectRow(val) {
      if (!val) return
      this.$emit('onSelect', { id: val.id, title: val.title })
    }
  },
  async mounted() {
    await this.loadMore()
    if (this.selectedId) {
      let row = this.newsList.find(x => x.id === this.selectedId)
      this.$nextTick(() => {
        this.$refs.tab.setCurrentRow(row)
      })
    }
  }
}
</script>

<style>
</style>
